#!/bin/bash
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.

set -ex

echo "binary path is ${binary_path}"

CURRENT_DIR=$(cd "$(dirname $0)" && pwd)
AGENT_HOME=${CURRENT_DIR}/../../../
AGENT_ROOT=${AGENT_HOME}/Agent
UNIX_TYPE_VERSION="AIX"

if [ ! -d "mkdir ${AGENT_ROOT}/open_src" ]; then
    mkdir -p ${AGENT_ROOT}/open_src
fi

if [ ! -d "mkdir ${AGENT_ROOT}/platform" ]; then
    mkdir -p ${AGENT_ROOT}/platform
fi

cp ${binary_path}/ThirdParty/Unix/${UNIX_TYPE_VERSION}/opensrc_agent.tar.gz ${AGENT_ROOT}/open_src/
cp ${binary_path}/ThirdParty/Unix/${UNIX_TYPE_VERSION}/platform_agent.tar.xz ${AGENT_ROOT}/platform/

if [ ! -d "${AGENT_ROOT}/open_src/boost" ]; then
    cd ${AGENT_ROOT}/open_src/
    gzip -d ${AGENT_ROOT}/open_src/opensrc_agent.tar.gz
    tar -xvf ${AGENT_ROOT}/open_src/opensrc_agent.tar
fi

if [ ! -d "${AGENT_ROOT}/platform/KMCV3_rel" ]; then
    cd ${AGENT_ROOT}/platform/
    tar -xvf ${AGENT_ROOT}/platform/platform_agent.tar.xz
fi

cd ${AGENT_ROOT}/build/

source ${AGENT_HOME}/Agent/build/env.sh
export OBJECT_MODE=64
bash ${AGENT_HOME}/Agent/build/agent_make_opensrc.sh
if [ $? -ne 0 ]; then
    echo "agent make open src fail."
    exit 1
fi
echo "agent make open src success."

sh ${AGENT_HOME}/Agent/build/agent_make_pre.sh
if [ $? -ne 0 ]; then
    echo "make pre failed!"
    exit 1
fi
echo "agent make pre success."

bash ${AGENT_HOME}/Agent/build/agent_pack_backup.sh no_opensrc
if [ $? -ne 0 ]; then
    echo "agent make src fail."
    exit 1
fi
echo "agent make src success."

if [ ! -d ${binary_path}/dependency/common ]; then
    mkdir -p ${binary_path}/dependency/common
fi
cp ${AGENT_HOME}/AGENT_PACK_TEMP/protectclient-AIX-ppc_64.tar.xz ${binary_path}/dependency/common/

echo "build in aix success"
exit 0